package com.myFwk.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myFwk.domain.SysPrivilege;
import com.myFwk.model.R;
import com.myFwk.service.serviceImpl.SysPrivilegeServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.util.Date;

/**
 * @Title:
 * @Description:
 * @Author: guowl
 * @version： 1.0
 * @Date:2021/9/2
 * @Copyright: Copyright(c)2021 RedaFlight.com All Rights Reserved
 */
@RestController
@Api(tags = "系统权限管理")
@RequestMapping("/privileges")
public class SysPrivilegeController {
    @Autowired
    private SysPrivilegeServiceImpl sysPrivilegeService;

    @GetMapping
    @ApiOperation(value = "分页查询权限数据")
    @PreAuthorize("hasAuthority(sys_privilege_query)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页显示大小"),
    })
    public R<Page<SysPrivilege>> findByPage(@ApiIgnore Page<SysPrivilege> page) {
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<SysPrivilege> pages = sysPrivilegeService.page(page);
        return R.ok(pages);
    }

    /**
     * @param sysPrivilege
     * @return
     */
    @PostMapping
    @ApiOperation(value = "新增一个权限")
    @PreAuthorize("hasAuthority(sys_privilege_create)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysPrivilege", value = "json的数据的值")
    })
    public R add(@RequestBody @Validated SysPrivilege sysPrivilege) {
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        sysPrivilege.setId(Long.valueOf(userId));
        sysPrivilege.setCreated(new Date());
        sysPrivilege.setLastUpdateTime(new Date());
        boolean save = sysPrivilegeService.save(sysPrivilege);
        if (save) {
            return R.ok();
        } else {
            return R.fail();
        }

    }


}
